<template>
  <div class="a3-page">
    <div class="tool-view">
      <n-scrollbar x-scrollable>
        <div class="tool-l">
          <span>站点名称</span>
          <n-select
            placeholder="选择站点名称"
            style="width: 100px"
            v-model:value="params.modelId"
            :options="stationList"
            @update:value="GetAllStationInfoFun"
          />
          <span>OP属性</span>
          <n-select
            placeholder="选择OP属性"
            style="width: 100px"
            v-model:value="params.stationId"
            :options="OPList"
          />
          <span>设备编码</span>
          <n-select
            placeholder="选择设备编码"
            style="width: 100px"
            v-model:value="devicecode"
            :options="deviceList"
          />
          <span>产品名称</span>
          <n-select
            placeholder="选择产品名称"
            style="width: 200px"
            v-model:value="params.productName"
            :options="productNameList"
            @update:value="GetProductSNListFun"
          />
          <span>SN码</span>
          <n-select
            placeholder="选择SN码"
            style="width: 200px"
            v-model:value="params.productSN"
            :options="productSNList"
          />
          <span>时间</span>
          <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
            <n-date-picker
              style="width: 345px"
              v-model:value="range"
              type="datetimerange"
              clearable
              @update:formatted-value="timeChange"
              :is-date-disabled="disablePreviousDate"
            />
          </n-config-provider>
        </div>
      </n-scrollbar>
      <div class="tool-r">
        <n-button
          :disabled="!isQuery"
          type="success"
          @click="handlePageChange(1)"
        >
          查询
        </n-button>
        <n-button color="#4aa6ac" @click="openWin(0)">添加邮箱</n-button>
        <div :class="['yellow', isQuery ? '' : 'un']" @click="DownFun(false)">
          下载
        </div>
        <div :class="['blue', isQuery ? '' : 'un']" @click="DownFun(true)">
          发送
        </div>
      </div>
    </div>
    <div class="table-view">
      <div class="select-view">
        <div class="view">
          <n-select
            placeholder="选择参数"
            class="n-select"
            style="width: 270px"
            v-model:value="selectValue"
            :options="titleList"
            @update:value="GetMobproductDataOneFun"
          />
        </div>
      </div>
      <div class="top-view">
        <Polyline v-if="echarlsList.length > 0" :data="echarlsList" />
        <div v-else style="flex: 1">1</div>
        <div class="text-view">
          <div v-if="store.superUser < 2" class="btn-tool">
            <div
              class="edit"
              @click="(editRemark = !editRemark), (remark1 = remark)"
            >
              {{ editRemark ? "取消" : "编辑" }}
            </div>
            <div
              v-if="editRemark"
              class="edit"
              @click="PostMobprambydevicecodeFun"
            >
              保存
            </div>
          </div>
          <div v-if="!editRemark" class="text">
            {{ remark }}
          </div>
          <n-input
            v-else
            class="textarea"
            placeholder="请输入备注"
            type="textarea"
            v-model:value="remark1"
            size="small"
            :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </div>
      </div>
      <div ref="container" class="bottom-view" :class="showTop ? '' : 'show'">
        <!-- v-if="data.length > 0" -->
        <div
          v-if="data.length > 0"
          class="line"
          :class="showTop ? 'top' : ''"
          @click="showTopFun"
        >
          <icons class="icon" name="top" />
        </div>
        <n-data-table
          remote
          :loading="loading"
          :data="data"
          :columns="columns"
          :single-line="false"
          :single-column="true"
          :pagination="pagination"
          :scroll-x="scrollX"
          @update:page="handlePageChange"
          :max-height="height"
        />
      </div>
    </div>
  </div>
  <n-modal
    :mask-closable="false"
    class="add-dialog"
    v-model:show="openDelDialog"
    :show-icon="false"
    preset="dialog"
    :on-close="closeWin"
    transform-origin="center"
    style="background: #60676c; width: 700px; color: #ffffff"
  >
    <template #header>
      <div class="title-font">
        {{ setType === 0 ? "添加邮箱" : "发送邮箱" }}
      </div>
    </template>
    <div v-if="setType === 0" class="notice-info">
      <div class="email-line">
        <div class="label">邮箱类型</div>
        <n-select
          class="select"
          placeholder="选择邮箱类型"
          v-model:value="emialParams.eMailType"
          :options="emailOptions"
        />
      </div>
      <div class="email-line">
        <div class="label">邮箱</div>
        <n-input
          v-model:value="emialParams.emailAddress"
          type="text"
          placeholder="请输入邮箱"
          size="large"
        />
      </div>
      <div class="email-line">
        <div class="label">密码</div>
        <n-input
          v-model:value="emialParams.password"
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          size="large"
        />
      </div>
      <div class="email-line">
        <div class="label">确认密码</div>
        <n-input
          v-model:value="emialParams.checkPassword"
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          size="large"
        />
      </div>
    </div>
    <div v-else class="notice-info">
      <div class="email-line">
        <div class="label">邮件主题</div>
        <n-input
          v-model:value="senParams.mailSubject"
          type="text"
          placeholder="请输入邮件主题"
          size="large"
        />
      </div>
      <div class="email-line">
        <div class="label">接收邮箱</div>
        <n-input
          v-model:value="senParams.mailTo"
          type="text"
          placeholder="请输入收件人邮箱"
          size="large"
        />
      </div>
    </div>
    <div v-if="setType === 0" class="footer">
      <n-button class="btn" @click="closeWin"> 取消 </n-button>
      <n-button class="btn" type="success" @click="SaveEMailAccountFun">
        确定
      </n-button>
    </div>
    <div v-else class="footer">
      <n-button class="btn" @click="closeWin"> 取消 </n-button>
      <n-button class="btn" type="success" @click="SendEmailFun">
        确定
      </n-button>
    </div>
  </n-modal>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import Polyline from "@/components/Echarts/Polyline.vue"; //折线
import { today } from "@/tools/radom";
import {
  GetAllStationInfo,
  GetProductNameList,
  GetProductSNList,
  GetPageA2Name,
  GetMobproductDataEx,
  GetMobproductDataOne,
  SendEmail,
  SaveEMailAccount,
  DownloadReportForm,
  GetEMailType,
  GetMobdevicelsBydevicetype,
  GetMobprambydevicecode,
  PostMobprambydevicecode,
} from "@/server";
import { zhCN, dateZhCN } from "naive-ui";
import { useAppStore } from "@/store/modules/user";
const route = useRoute();
const modelId = computed(() => route.params.id);
const store = useAppStore();
const openMore = ref(false);
const stationList = ref([]) as any; //站台列表
const OPList = ref([]) as any; //站台列表
const range = ref<[number, number]>([Date.now(), Date.now()]);
const params = ref({
  modelId: null,
  stationId: null,
  productName: null,
  productSN: null,
  startTime: today(),
  endTime: today(),
}) as any;
const emialParams = ref({
  emailAddress: "",
  password: "",
  checkPassword: "",
}) as any;
const pagination = ref({
  page: 1,
  pageCount: 1,
  pageSize: 20,
  pageSlot: 7,
});
const senParams = ref({
  mailTo: "",
  mailSubject: "",
  filePath: "",
});
watch(
  () => modelId.value,
  () => {
    params.value = {
      modelId: null,
      stationId: null,
      productName: null,
      productSN: null,
      startTime: today(),
      endTime: today(),
    };
    devicecode.value = null;
    GetMobdevicelsBydevicetypeFun();
    GetPageA2NameFun();
    GetProductNameListFun();
  }
);
const devicetype = computed(() => route.params.remark);
const devicecode = ref(null) as any;
const emailOptions = ref([]) as any;
const openDelDialog = ref(false);
const showTop = ref(false);
const data = ref([]) as any;
const columns = ref() as any;
const scrollX = ref(2000);
const loading = ref(false);
const productNameList = ref([]) as any; //产品名称列表;
const productSNList = ref([]) as any; //产品SN码列表
const titleList = ref([]) as any; //参数
const closeWin = () => {
  openDelDialog.value = false;
  openMore.value = false;
};
const setType = ref(0);
const openWin = (type: number) => {
  openDelDialog.value = true;
  setType.value = type;
  emialParams.value = {
    emailAddress: "",
    password: "",
    checkPassword: "",
  };
};
const timeChange = (e: any) => {
  params.value.startTime = e[0];
  params.value.endTime = e[1];
};
const showTopFun = () => {
  showTop.value = !showTop.value;
  if (showTop.value) {
    if (titleList.value.length > 0) {
      // GetMobproductDataOneFun(titleList.value[0].value);
    }
  }
  setTimeout(() => {
    updateHeight();
  }, 300);
};
const isQuery = computed(() => {
  const { modelId, stationId, productName, productSN } = params.value;
  return modelId && stationId && productName && productSN;
});
const handlePageChange = (curent: number) => {
  pagination.value.page = curent;
  GetMobproductDataExFun();
};
const height = ref(0);
const container = ref(null) as any;
const updateHeight = () => {
  if (container.value) {
    const containerHeight = container.value.offsetHeight;
    height.value = containerHeight - 120;
  }
};
const disablePreviousDate = (ts: number) => {
  return ts > Date.now();
};
onMounted(() => {
  updateHeight();
  window.addEventListener("resize", updateHeight);

  // Cleanup listener on component unmount
  return () => {
    window.removeEventListener("resize", updateHeight);
  };
});
const selectValue = ref(null) as any;
const lock = ref(false);
const unLock = () => {
  setTimeout(() => {
    lock.value = false;
  }, 1000);
};
//查询数据
const GetMobproductDataExFun = async () => {
  loading.value = true;
  if (lock.value) {
    return false;
  }
  lock.value = true;
  const param = {
    productsn: params.value.productSN,
    opcode: params.value.stationId,
    devicecode: devicecode.value,
    devicetype: devicetype.value,
    page: pagination.value.page,
    pagesize: pagination.value.pageSize,
    begindate: params.value.startTime,
    enddate: params.value.endTime,
  };
  selectValue.value = null;
  echarlsList.value = [];
  editRemark.value = false;
  remark.value = "";
  remark1.value = "";
  if (showTop.value) {
    showTopFun();
  }
  const res: any = await GetMobproductDataEx(param);
  if (res.result.isSuccess) {
    loading.value = false;
    columns.value = [];
    columns.value = res.result.header.map((e: any, index: number) => {
      if (e.key === "id") {
        e.width = 100;
        e.fixed = "left";
        e.titleAlign = "center";
        e.align = "center";
      } else {
        e.width = 140;
        e.titleAlign = "center";
        e.align = "center";
        e.ellipsis = {
          tooltip: true,
        };
      }
      return e;
    });
    //因为value很多一样的所以
    const arr = columns.value
      .filter((e: any) => e.remark)
      .map((e: any) => {
        return { value: generateRandomString() + e.remark, label: e.title };
      });

    // 使用 Set 进行去重 // 使用 Set 去除重复项，然后通过 Array.from 转回数组
    titleList.value = arr;
    console.log(JSON.stringify(titleList));

    //  Array.from(
    //   new Set(arr.map((obj: any) => JSON.stringify(obj))),
    //   (jsonString: any) => JSON.parse(jsonString) as any
    // );

    scrollX.value = columns.value.length * 140 - 80;
    const list = res.result.result;
    const viewmodels = list.map((e: any) => {
      const list1 = e.viewmodels;
      const list2 = e.viewmodelsplc;
      delete e.viewmodels;
      delete e.viewmodelsplc;
      const obbj: any = e;
      for (let index = 0; index < list1.length; index++) {
        const element = list1[index];
        obbj[element.indicator] = element.parmvalue;
      }
      for (let index = 0; index < list2.length; index++) {
        const element = list2[index];
        obbj[element.indicator] = element.parmvalue;
      }
      return obbj;
    });

    data.value = viewmodels;
    pagination.value.pageCount = Math.ceil(
      res.result.otherResult / param.pagesize
    );
    if (data.value.length === 0) {
      store.info("未查询到数据"); // 错误提示
    }
    unLock();
  } else {
    unLock();
    loading.value = false;
    store.error(res.result.message); // 错误提示
  }
};
function generateRandomString() {
  // 生成数字和字母的字符集
  const characters =
    "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  // 初始化结果字符串
  let result = "";

  // 随机生成10位字符
  for (let i = 0; i < 10; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }

  return result;
}
//获取所有站点配置
const GetAllStationInfoFun = async () => {
  const res: any = await GetAllStationInfo({
    modelId: params.value.modelId,
  });
  if (res.result.isSuccess) {
    params.value.stationId = null;
    OPList.value = res.result.result.map((e: any) => {
      e.value = e.stationName;
      e.label = e.stationName;
      return e;
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const echarlsList = ref([]) as any;
const deviceInfo = ref({ indicator: "", parmtype: "" });
const GetMobproductDataOneFun = async (modey: string) => {
  const titleData = titleList.value.find((e: any) => e.value === modey);
  deviceInfo.value.indicator = titleData.label;
  deviceInfo.value.parmtype = titleData.value.substring(10);
  const param = {
    productsn: params.value.productSN,
    opcode: params.value.stationId,
    devicecode: devicecode.value,
    devicetype: devicetype.value,
    indicator: deviceInfo.value.indicator,
    parmtype: deviceInfo.value.parmtype,
    page: 1,
    pagesize: 100,
  };
  const res: any = await GetMobproductDataOne(param);
  if (res.result.isSuccess) {
    echarlsList.value = res.result.result;
  } else {
    store.error(res.result.message); // 错误提示
  }
  GetMobprambydevicecodeFun();
};
//获取产品名称列表
const GetProductSNListFun = async () => {
  const res: any = await GetProductSNList({
    productName: params.value.productName,
  });
  if (res.result.isSuccess) {
    params.value.productSN = null;
    productSNList.value = res.result.result.map((e: any) => {
      return { value: e, label: e, id: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取产品名称列表
const GetProductNameListFun = async () => {
  const res: any = await GetProductNameList({});
  if (res.result.isSuccess) {
    productNameList.value = res.result.result.map((e: any) => {
      return { value: e, label: e, id: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};

//获取初始化数据1
const GetPageA2NameFun = async () => {
  const res: any = await GetPageA2Name({});
  if (res.result.isSuccess) {
    stationList.value = res.result.result.map((e: any) => {
      e.value = e.modelId;
      e.label = e.name;
      return e;
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取初始化数据1
const GetEMailTypeFun = async () => {
  const res: any = await GetEMailType({});
  if (res.result.isSuccess) {
    emailOptions.value = res.result.result.map((e: any) => {
      return { value: e, label: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
GetEMailTypeFun();
//获取设备类型
const deviceList = ref([]) as any;
const GetMobdevicelsBydevicetypeFun = async () => {
  const res: any = await GetMobdevicelsBydevicetype({
    devicetype: devicetype.value,
  });
  if (res.result.isSuccess) {
    deviceList.value = res.result.result.map((e: any) => {
      return { value: e.devicecode, label: e.devicecode };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};

const editRemark = ref(false);
const remark = ref("");
const remark1 = ref("");
const GetMobprambydevicecodeFun = async () => {
  editRemark.value = false;
  const res: any = await GetMobprambydevicecode({
    devicecode: devicecode.value,
    indicator: deviceInfo.value.indicator,
    parmtype: deviceInfo.value.parmtype,
  });
  if (res.result.isSuccess) {
    remark.value = res.result.result.remark;
    remark1.value = res.result.result.remark;
  } else {
    store.error(res.result.message); // 错误提示
  }
};

const PostMobprambydevicecodeFun = async () => {
  const res: any = await PostMobprambydevicecode({
    remark: remark1.value,
    devicecode: devicecode.value,
    indicator: deviceInfo.value.indicator,
    parmtype: deviceInfo.value.parmtype,
  });
  if (res.result.isSuccess) {
    GetMobprambydevicecodeFun();
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//下载报表
const DownFun = async (type?: boolean) => {
  if (!isQuery.value) {
    return false;
  }
  if (type) {
    openDelDialog.value = true;
    setType.value = 1;
  }

  const param = {
    productsn: params.value.productSN,
    opcode: params.value.stationId,
    devicecode: devicecode.value,
    begindate: params.value.startTime,
    enddate: params.value.endTime,
  };
  const res: any = await DownloadReportForm(param);
  if (res.result.isSuccess) {
    if (type) {
      senParams.value.filePath = res.result.otherResult;
    } else {
      downloadXLSX(res.result.result);
    }
  } else {
    store.error(res.result.message); // 错误提示
  }
};
async function downloadXLSX(url: string) {
  let fileName = url.slice(url.lastIndexOf("/") + 1); // 这里是通过从后端获取到的 url  地址中截出来原本的文件名
  const link = document.createElement("a");
  link.href = url;
  // 下载文件的名称及文件类型后缀
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  //在资源下载完成后 清除 占用的缓存资源
  window.URL.revokeObjectURL(link.href);
  document.body.removeChild(link);
}
//SaveEMailAccount
const SaveEMailAccountFun = async () => {
  const { eMailType, emailAddress, password, checkPassword } =
    emialParams.value;
  if (!eMailType || !emailAddress || !password || !checkPassword) {
    store.warning("请输入完整信息"); // 错误提示
    return false;
  }
  if (password !== checkPassword) {
    store.warning("两次密码输入不一致"); // 错误提示
    return false;
  }
  const res: any = await SaveEMailAccount(emialParams.value);
  if (res.result.isSuccess) {
    openDelDialog.value = false;
    store.success(res.result.message); // 错误提示
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//发送邮件
const SendEmailFun = async () => {
  const { mailTo, mailSubject, filePath } = senParams.value;
  if (!mailTo) {
    store.warning("请输入收件人邮箱"); // 错误提示
    return false;
  }
  if (!mailSubject) {
    store.warning("请输入邮件主题"); // 错误提示
    return false;
  }
  if (!filePath) {
    store.warning("Excle地址不存在"); // 错误提示
    return false;
  }
  const res: any = await SendEmail(senParams.value);
  if (res.result.isSuccess) {
    store.success(res.result.message); // 错误提示
    openDelDialog.value = false;
  } else {
    store.error(res.result.message); // 错误提示
  }
};
GetMobdevicelsBydevicetypeFun();
GetPageA2NameFun();
GetProductNameListFun();
</script>

<style lang="less" scoped>
.a3-page {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #ffffff;
  :deep(.n-data-table__pagination) {
    padding-right: 20px;
  }
  .tool-view {
    display: flex;
    height: 60px;
    align-items: center;
    justify-content: space-between;
    background: #e3e3e3;
    backdrop-filter: blur(32px);

    .tool-l {
      min-width: 1650px;
      display: flex;
      align-items: center;
      flex: 1;
      height: 60px;

      span {
        font-size: 18px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #1c262d;
        line-height: 25px;
        margin: 0 12px 0 20px;
      }
    }

    .tool-r {
      display: flex;
      align-items: center;
      justify-content: space-between;
      min-width: 312px;
      padding-right: 20px;
      .un {
        opacity: 0.7;
        cursor: no-drop !important;
      }
      .yellow {
        &:hover {
          opacity: 0.8;
        }
        cursor: pointer;
        background: #ee9708;
        padding: 7px 15px;
        color: #ffffff;
        border-radius: 3px;
        pointer-events: all;
      }
      .blue {
        &:hover {
          opacity: 0.8;
        }
        cursor: pointer;
        background: #01c0e4;
        padding: 7px 15px;
        color: #ffffff;
        border-radius: 3px;
        pointer-events: all;
      }
    }
  }
  .table-view {
    position: relative;
    height: calc(100% - 60px);
    .select-view {
      padding: 10px 0;
      .view {
        margin: auto;
        width: 270px;
        height: 32px;
        background: #5d6a73;
        box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.08),
          0px 1px 3px 0px rgba(25, 15, 15, 0.07),
          0px 3px 5px 0px rgba(0, 0, 0, 0.05);
        .n-select {
          :deep(.n-base-selection-label) {
            background: none;
            .n-base-selection-input {
              color: #ffffff;
            }
          }
        }
      }
    }
    .top-view {
      overflow: hidden;
      height: calc(40% - 70px);
      display: flex;
      align-items: center;
      justify-content: center;
      padding-bottom: 10px;
      .text-view {
        margin-right: 20px;
        .btn-tool {
          position: absolute;
          left: 0;
          top: 0;
          .edit {
            cursor: pointer;
            background-color: #1c262d;
            color: #ffffff;
            font-size: 12px;
            padding: 5px 10px;
            margin-bottom: 20px;
          }
        }
        position: relative;
        width: 40%;
        height: 100%;
        background: #f9f9f9;
        border-radius: 3px;
        .text {
          padding: 30px;
          text-align: left;
        }
        .textarea {
          height: 100%;
          width: calc(100% - 50px);
          margin-left: 50px;
          text-align: left;
        }
      }
    }
    .line {
      display: flex;
      align-items: center;
      justify-content: center;
      &.top {
        transform: rotate(0deg);
      }
      transform: rotate(180deg);
      color: #ffffff;
      background: #dbdbdb;
      height: 20px;
      position: relative;
      .icon {
        position: absolute;
        width: 20px;
        height: 20px;
      }
    }
    .bottom-view {
      &.show {
        height: 100%;
      }
      background: #ffffff;
      width: 100%;
      position: absolute;
      height: 60%;
      bottom: 0;
      transition: height 0.3s;
    }
  }
}
.add-dialog {
  .title-font {
    font-size: 24px;
    color: #02a8ae;
  }
  .notice-info {
    margin: 20px 0 40px;
    .email-line {
      display: flex;
      align-items: center;
      padding: 10px 0;
      :deep(.n-input) {
        background: none !important;
        input {
          color: #ffffff !important;
        }
      }
      .select {
        :deep(.n-base-selection-label) {
          background: none;
          .n-base-selection-input {
            color: #ffffff;
          }
        }
      }
      .label {
        text-align: right;
        width: 100px;
        margin-right: 20px;
      }
    }
  }
  .footer {
    margin-top: 10px;
    display: flex;
    justify-content: center;
    .btn {
      margin: 0 10px;
      width: 100px;
      height: 36px;
      font-size: 18px;
      color: #fff;
    }
  }
}
:deep(.n-data-table-td) {
  border-bottom: 1px solid rgba(239, 239, 245, 1) !important;
}
:deep(.n-step-indicator) {
  background: #02a8ae;
  box-shadow: 0 0 0 1px #02a8ae;
}
:deep(.n-step-splitor) {
  background: rgba(0, 0, 0, 0.15);
}
:deep(.n-step-content-header) {
  margin-top: 0 !important;
}
:deep(.n-step-content-header__title) {
  font-size: 22px;
  font-family: SourceHanSansCN, SourceHanSansCN;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  line-height: 33px;
}
</style>
